/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-05-30 19:23:01
 * @LastEditTime: 2022-05-31 15:04:07
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import { MetadataAliasReducer } from '../reducers/MetadataAliasReducer';
import {
  ADD_ALIAS,
  DELETE_ALIAS,
  EDIT_ALIAS,
  SET_ALIAS_LIST,
  SET_SELECTED_ITEM
} from '../constants';
import { addAlias, deleteAlias, editAlias, fetchAliasListByPage } from '@/api/metadata';

const initialState = {
  // 选中的表格条目
  selectItems: [],
  // 别名列表
  aliasList: []
};

const MetadataAliasContext = createContext();

const MetadataAliasContextProvider = (props) => {
  const [state, dispatch] = useReducer(MetadataAliasReducer, initialState);

  const actions = {
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取别名列表
     */
    getAliasList(params) {
      return new Promise((resolve, reject) => {
        fetchAliasListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_ALIAS_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 增加别名
     * @param {*} params 增加的别名
     */
    addAliasFunc(params) {
      return new Promise((resolve, reject) => {
        addAlias(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_ALIAS, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    editAliasFunc(params) {
      return new Promise((resolve, reject) => {
        editAlias(params)
          .then((res) => {
            const { data } = res;
            const { id } = res.data;
            dispatch({ type: EDIT_ALIAS, id, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    delAliasFunc(id, content = '确认删除选中的别名？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteAlias(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_ALIAS, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  // watch listQuery来加载排序列表
  useEffect(() => {}, []);

  return (
    <MetadataAliasContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </MetadataAliasContext.Provider>
  );
};

export const useMetadataAliasContext = () => {
  return useContext(MetadataAliasContext);
};

export { MetadataAliasContext, MetadataAliasContextProvider };
